from PySide6.QtWidgets import QGridLayout, QGroupBox
from model.Student import Student
from view.BehaviorButton import BehaviorButton

class BehaviorBox(QGridLayout):
    def __init__(self, main_window, title="行为记录"):
        super().__init__()
        self._container = QGroupBox(title)
        self._container.setLayout(self)
        self.main_window = main_window
        self.max_cols = 3
        self.current_row = 0
        self.current_col = 0
        self._buttons = []
        self.add_button("行为按钮")

    def add_button(self, text):
        btn = BehaviorButton(text)
        btn.clicked_with_count.connect(self.main_window.sync_to_current_student)
        
        if self.current_col >= self.max_cols:
            self.current_row += 1
            self.current_col = 0
            
        self.addWidget(btn, self.current_row, self.current_col)
        self.current_col += 1
        self._buttons.append(btn)

    def clear_all(self):
        """清空所有按钮和布局"""
        # 1. 移除所有按钮组件
        for i in reversed(range(self.count())):
            widget = self.itemAt(i).widget()
            if widget:
                widget.deleteLater()
        
        # 2. 重置布局状态
        self.current_row = 0
        self.current_col = 0
        self._buttons.clear()

   
    def update_buttons_from_data(self, student: Student, date_str: str):
        """
        根据学生对象和日期更新行为按钮
        :param student: Student对象（使用date_records数据结构）
        :param date_str: 日期字符串(yyyyMMdd格式)
        """
        # 1. 从Student的date_records获取目标日期的行为数据
        date_record = student.date_records.get(date_str, {})
        behavior = date_record.get("behavior", {})
        # 2. 遍历所有行为按钮并更新计数
        for btn in self._buttons:
            btn_count = behavior.get(btn.title, 0)
            btn.update_count(btn_count)
    
    def get_behavior_data(self, filter_zero=True):
        return {btn.title: btn.count for btn in self._buttons 
                if not filter_zero or btn.count > 0}
           

